<template>
    <div class="app-container">
        <levelbar></levelbar>
        <div class="form-box">
            <div class="form-title">添加员工信息</div>
            <el-form label-width="100px" class="app-content form" :rules="rules" :model="ruleForm" ref="ruleForm">
                <div class="form-item">
                    <div class="form-item-title">
                        <span class="title-level">基础信息</span>
                    </div>
                    <div class="form-content">
                        <el-row :gutter="41" class='input-hidden'>
                            <el-col :span="10">
                                <el-input name="old-userName" type="text" disabled ></el-input>
                                <el-input name="old-pwd" type="password" disabled ></el-input>
                            </el-col>
                        </el-row>
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="姓名" prop="userName">
                                    <el-popover placement="top-start" trigger="focus" content="字符长度不大于20个">
                                        <el-input v-model="ruleForm.userName" placeholder="请输入名字" :maxlength="20" slot="reference" style="width:95%"></el-input>
                                    </el-popover>        
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="登录名" prop="loginName">
                                    <el-popover placement="top-start" trigger="focus" content="字符长度不大于30个">
                                        <el-input v-model="ruleForm.loginName" placeholder="请输入登录名" :maxlength="30" slot="reference" style="width:95%"></el-input>
                                    </el-popover>       
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="密码" prop="initialPass">
                                    <el-popover placement="top-start" trigger="focus" content="由6~16位英文或数字所组成">
                                        <el-input type="password" v-model="ruleForm.initialPass" placeholder="请输入初始密码" :maxlength="16" auto-complete="off" slot="reference" style="width:95%"></el-input>
                                    </el-popover>    
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="确认密码" prop="checkPass">
                                    <el-popover placement="top-start" trigger="focus" content="由6~16位英文或数字所组成">
                                        <el-input type="password" v-model="ruleForm.checkPass" placeholder="请确认密码" :maxlength="16" auto-complete="off" slot="reference" style="width:95%"></el-input>
                                    </el-popover>    
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="角色" prop="roleId">
                                    <el-select v-model="ruleForm.roleId" placeholder="请选择" style="width:95%">
                                        <el-option v-for="item in ruleForm.dataType" :key="item.pId" :label="item.sName" :value="item.pId"> </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                    <div class="form-item-title">
                        <span class="title-level">负责区域</span>
                    </div>
                    <div class="form-content">
                        <el-row v-for="(site,index) in ruleForm.dataAgent" :gutter="21" :key="site.key" ref='addSchoolLeader'>
                            <el-col :span="7">
                                <el-form-item label="所选省：" :prop="'dataAgent[' + index + '].fProvinceId'" :rules="{required: true, message: '所选省不能为空', trigger: 'change'}">
                                    <province @change="areaChange(site, index)" :disabledOptions="site.disabledPid" :emptyOption="false" v-model="site.fProvinceId" ></province>
                                </el-form-item>
                            </el-col>
                            <el-col :span="7"  :offset="1">
                                <el-form-item label="所选市：">
                                    <city @change="areaChange(site, index)" :disabledOptions="site.disabledCid" :emptyOption="false" v-model="site.fCityId" :province="site.fProvinceId"></city>
                                </el-form-item>
                            </el-col>
                            <el-col :span="7" :offset="1">
                                <el-form-item label="所选区县：">
                                    <region @change="areaChange(site, index)" :disabledOptions="site.disabledAid" :emptyOption="false" v-model="site.fAreaId" :city="site.fCityId"></region>
                                </el-form-item>
                            </el-col>
                            <div class="delBtn"><i class="el-icon-delete" @click.prevent="removeDomain(index)" v-if='index != 0'></i></div>
                        </el-row>    
                        <div style="margin-left:25px">
                            <el-button type="text" @click="addArea" class="addBtn"><i class="el-icon-plus"></i>继续添加</el-button>
                        </div>
                    </div>
                    <div class="form-item">
                        <div class="footer">
                            <el-button @click="resetForm">取消</el-button>
                            <el-button type="primary" @click="submitForm('ruleForm')" :loading="loadingBtn">确认</el-button>
                        </div>
                    </div>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script>
import Levelbar from '../layout/Levelbar';
import { saveCompanyStaff, findAccountIsExist, findSysRoles, findAgentAreaByOrgUserId} from 'api/staffManagement';
import province from 'components/CascadeRegiones/province';
import city from 'components/CascadeRegiones/city';
import region from 'components/CascadeRegiones/region';
import { mapGetters } from 'vuex';
import sha256 from 'sha256';
export default{
    name: 'addStaff',
    components: {Levelbar, province, city, region},
    data() {
        // 密码一致判断
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            } else {
                let pass = /^[0-9a-zA-Z]{6,16}$/;
                if (!pass.test(value)) {
                    callback(new Error('密码格式不正确，密码由6~16位英文或数字所组成'));
                }
                if (this.ruleForm.checkPass !== '') {
                    this.$refs.ruleForm.validateField('checkPass');
                }
                callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.ruleForm.initialPass) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        var loginUserName = (rule, value, callback) => {
            value = value.replace(/\s/g, '');
            if (!value) {              
                callback(new Error('请输入登录名'));
                return               
            } else {
                findAccountIsExist(value).then(res => {
                    callback();
                }).catch(e => {
                    callback(new Error('用户名已存在'));
                }) 
            }
        };
        return {
            ruleForm: {
                userName: '', // 用户名
                loginName: '', // 登录名
                initialPass: '', // 密码
                checkPass: '', // 确认密码
                // type: [],
                roleId: '', // 角色
                findCity: [], // 市列表
                findArea: [], // 区列表
                province: [], // 省列表
                dataType: [], // 角色列表
                dataAgent: []
                
            },
            loadingBtn: false,
            rules: {
                userName: [
                    {required: true, message: '请填写姓名', trigger: 'blur'},
                    { pattern: /^[^ ]+$/, message: '请勿输入空格', trigger: 'change'}
                ],
                loginName: [
                    {required: true, message: '', validator: loginUserName, trigger: 'blur' },
                    { pattern: /^[^ ]+$/, message: '请勿输入空格', trigger: 'change'} 
                ],
                initialPass: [
                    {required: true, message: '', validator: validatePass, trigger: 'blur' },
                    { pattern: /^[^ ]+$/, message: '请勿输入空格', trigger: 'change'}
                ],
                checkPass: [
                    {required: true, message: '', validator: validatePass2, trigger: 'blur' },
                    { pattern: /^[^ ]+$/, message: '请勿输入空格', trigger: 'change'}
                ],
                roleId: [
                    {required: true, message: '角色不能为空', trigger: 'change'}
                ]
            }
        }
    },
    created() {
        // this.searchProvice();
        this.getroleType();
        this.searchInfo();
        this.addArea();
        
    },
    computed: {
        ...mapGetters([
            'uid'
        ])
    },
    methods: {
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    
                    this.$confirm('确定要提交吗?', ' ', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消'
                    }).then(() => {
                        var dataAgentList = []
                        for (let i = 0;i< this.ruleForm.dataAgent.length;i++) {
                            let obj = {
                                fProvinceId: this.ruleForm.dataAgent[i].fProvinceId,
                                fCityId: this.ruleForm.dataAgent[i].fCityId,
                                fAreaId: this.ruleForm.dataAgent[i].fAreaId
                            }
                            dataAgentList.push(obj)
                        }
                        this.loadingBtn = true;
                        /**
                         * 密码加密 by cuihd 20180531
                         */
                        const pwd = sha256(this.ruleForm.initialPass);
                        saveCompanyStaff(
                                this.ruleForm.userName,
                                this.ruleForm.loginName,
                                pwd,
                                this.ruleForm.roleId,
                                dataAgentList
                        ).then(response => {
                            this.loadingBtn = false;
                            this.$message({
                                type: 'success',
                                message: '添加成功!'
                            })
                            this.$store.dispatch('UpdateCache');// 添加
                            this.$router.push('staffManagementes');
                        });
                    }).catch(() => {
                        this.loadingBtn = false;
                        this.$message.info('已取消');
                    });
                } else {
                    return false;
                }
            });
        },
        // 角色查询
        getroleType() {
            findSysRoles('2', '0').then(response => {
                let roleId = response.data.content;
                let select = {
                    sName: '请选择',
                    pId: ''
                }
                roleId.unshift(select);
                this.ruleForm.dataType = roleId;
            });
        },
        // // 查询省市区
        searchInfo() {

            findAgentAreaByOrgUserId(this.$route.params.orgUserId).then(response => {
                if (response.data.status==200) {
                    this.ruleForm.fProvinceId = response.data.content.provinceId;
                    this.ruleForm.fCityId = response.data.content.cityId;
                    this.ruleForm.fAreaId = response.data.content.areaId;
                } else {
                    this.$message({
                        type: 'warning',
                        message: response.data.errorMsg
                    })
                }
            });
        },
        // 添加负责区域
        addArea() {
            if (this. ruleForm.dataAgent.length >= 50) {
                this.$message({
                    message: '最多只能添加50个负责区域！'
                })
                return;
            }
            let area = {
                fProvinceId: null,
                fCityId: null,
                fAreaId: null,
                disabledPid: [],
                disabledCid: [],
                disabledAid: [],
                findCity: [],
                findArea: []
            };
            area.disabledPid.length = this.ruleForm.dataAgent.length;
            area.disabledCid.length = this.ruleForm.dataAgent.length;
            area.disabledAid.length = this.ruleForm.dataAgent.length;
            console.log(this.ruleForm.dataAgent, '+++=')
            this.ruleForm.dataAgent.forEach((item, index) => {
                if (item.fAreaId) {
                    console.log(area.disabledAid, 'area.disabledAid=======')
                    area.disabledAid.splice(index, 1, item.fAreaId);
                } else if (item.fCityId) {
                    area.disabledCid.splice(index, 1, item.fCityId);
                } else if (item.fProvinceId) {
                    area.disabledPid.splice(index, 1, item.fProvinceId);
                }
            });
            this.ruleForm.dataAgent.push(area);
        },

        // 删除添加负责区域
        removeDomain(index) {
            this.ruleForm.dataAgent.splice(index, 1);
        },
    // 跳转
          // 取消
        resetForm() {
            this.$router.push({path: '/staffManagement'});
        },
        areaChange(row, index) {
            this.ruleForm.dataAgent.forEach((item, i) => {
                if (i !== index) {
                    item.disabledAid.length = this.ruleForm.dataAgent.length;
                    item.disabledCid.length = this.ruleForm.dataAgent.length;
                    item.disabledPid.length = this.ruleForm.dataAgent.length;

                    if (row.fAreaId) {
                        item.disabledAid.splice(index, 1, row.fAreaId);
                        item.disabledCid.splice(index, 1, null);
                        item.disabledPid.splice(index, 1, null);
                    } else if (row.fCityId) {
                        item.disabledAid.splice(index, 1, null);
                        item.disabledCid.splice(index, 1, row.fCityId);
                        item.disabledPid.splice(index, 1, null);
                    } else if (row.fProvinceId) {
                        item.disabledAid.splice(index, 1, null);
                        item.disabledCid.splice(index, 1, null);
                        item.disabledPid.splice(index, 1, row.fProvinceId);
                    } else {
                        item.disabledAid.splice(index, 1, null);
                        item.disabledCid.splice(index, 1, null);
                        item.disabledPid.splice(index, 1, null);
                    }
                }
            });
        }
    }
}
</script>

<style lang="scss" scoped>
.app-container {
  position: relative;
  padding: 20px 20px 10px;
  $bgcolor: #fff;

  @mixin showTitle() {
    background: $bgcolor;
    box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
    -webkit-box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
  }
  .form-box {
    padding: 0 50px;
    @include showTitle();
    .form-title {
        padding-top:8px;
        text-align: center;
        font-size: 18px;
        color: #333;
        line-height: 72px;
        font-weight: bold;
        font-family: Microsoft YaHei;
        border-bottom: 1px solid #ddd;
    }
    .form {
        .form-item {
            padding-bottom: 40px;
            .form-item-title {
                margin: 40px 0;
                font-size: 14px;
                color: #333;
                line-height: 14px;
                border-left: 4px solid #ff5e2c;
                text-indent: 16px;
            
                .note-css {
                    vertical-align: middle;
                    display: inline-block;
                    width: 4px;
                    height: 14px;
                    margin-right: 26px;
                    border-left: 3px solid #ff5e2c;
                }
            
            }
            .warn-infor{
                font-size: 14px;
                color: #333;
            }
            .delBtn {
                display: inline-block;
                height: 36px;
                width: 16px;
                color:#999;
                line-height: 38px;
                margin-left:25px;
                i {
                    cursor: pointer;
                }
            }
            .addBtn{
                margin-left:74px;
                font-size:14px;
                color:#ff5e2c;
            }
            .footer {
                //float: right;
                text-align: center;
                margin-top: 40px;
            }
        }
        .input-hidden {
            visibility: hidden;
            position: absolute;
            z-index: -1;
        }
    }
  }
}

</style>